<template>
  <div>
    <el-row :gutter="15">
      <el-form ref="elForm" :model="dataForm" :rules="dataRule" size="small" label-width="100px" label-position="right"
        :disabled="setting.readonly">
        <template v-if="!loading && formOperates">
          <el-col :span="14" v-if="judgeShow('title')">
            <el-form-item label="信息标题" prop="title">
              <el-input v-model="dataForm.title" placeholder="请输入信息标题" :disabled="judgeWrite('title')" clearable
                :style='{"width":"100%"}' :maxlength="50">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14" v-if="judgeShow('typeId')">
            <el-form-item label="信息类型" prop="typeId">
              <el-select v-model="dataForm.typeId" placeholder="请选择信息类型" :disabled="judgeWrite('typeid')" clearable
                :style='{"width":"100%"}' filterable @focus="getAssoInfoTypeListData()">
                <el-option v-for="(item, index) in typeIdOptions" :key="index" :label="item.name" :value="item.id" :disabled="item.enabledMark == 0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="14" v-if="judgeShow('source')">
            <el-form-item label="作者/来源" prop="source">
              <el-input v-model="dataForm.source" placeholder="请输入作者/来源" :disabled="judgeWrite('source')" clearable :maxlength="20"
                :style='{"width":"100%"}'>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14" v-if="judgeShow('contentAbstract')">
            <el-form-item label="内容摘要" prop="contentAbstract">
              <el-input v-model="dataForm.contentAbstract" placeholder="请输入内容摘要" :disabled="judgeWrite('contentabstract')" :maxlength="100"
                clearable :style='{"width":"100%"}'>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('picture')">
            <el-form-item label="信息图片" prop="picture">
              <JNPF-UploadImg v-model="dataForm.picture" :fileSize="5" :disabled="judgeWrite('picture')" sizeUnit="MB" @change="uploadImgChange"></JNPF-UploadImg>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('detailedDescribe')">
            <el-form-item label="信息详情" prop="detailedDescribe">
              <JNPF-Quill v-model="dataForm.detailedDescribe" placeholder="请输入" @input="uploadQuill"
                :disabled="judgeWrite('detaileddescribe')">
              </JNPF-Quill>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('fileJson')">
            <el-form-item label="上传附件" prop="fileJson">
              <JNPF-UploadFz v-model="dataForm.fileJson" :fileSize="5" :disabled="judgeWrite('filejson')"
                :showTip="true" sizeUnit="MB" :limit="9" buttonText="点击上传">
              </JNPF-UploadFz>
            </el-form-item>
          </el-col>
        </template>
      </el-form>
    </el-row>
    <UserBox v-if="userBoxVisible" ref="userBox" @submit="submit" />
  </div>
</template>
<script>
  import { getAssoInfoTypeList } from '@/api/asso/info/category'
  import request from '@/utils/request'
  export default {
    name: 'assoinfolistForm',
    components: {},
    props: [],
    data() {
      return {
        visible: false,
        loading: false,
        setting: {},
        eventType: '',
        userBoxVisible: false,
        currTableConf: {},
        addTableConf: {},
        tableRows: {},
        dataForm: {
          id: '',
          flowId: '',
          status: 1,
          freeapproveruserid: '',
          flowUrgent: 1,
          title: undefined,
          typeId: undefined,
          source: this.$store.state.user.userInfo.userName,
          contentAbstract: undefined,
          picture: [],
          detailedDescribe: undefined,
          fileJson: [],
        },
        tableRequiredData: {},
        dataRule: {
          title: [{
            required: true,
            message: '信息标题',
            trigger: 'blur'
          }, ],
          typeId: [{
            required: true,
            message: '选择类型',
            trigger: 'change'
          }, ],
          picture: [{
            required: true,
            message: '请至少选择一个',
            trigger: 'change'
          }, ],
          detailedDescribe: [{
            required: true,
            message: '请输入',
            trigger: 'change'
          }, ],
        },
        typeIdOptions: [],
      }
    },
    computed: {
      formOperates() {
        return this.setting.formOperates
      }
    },
    watch: {},
    created() {},
    mounted() {},
    methods: {
      getAssoInfoTypeListData() {
        let _query = {
          superQueryJson: '',
          currentPage: 1,
          pageSize: 20,
          sort: "desc",
          sidx: ""
        };
        request({
          url: `/api/zgyf/AssoInfoType/Selector`,
          method: 'get'
        }).then(res => {
          res.data.list.forEach(item => {
            item.fullName = item.name
          })
          this.typeIdOptions = JSON.parse(JSON.stringify(res.data.list))
        })
      },
      judgeShow(id) {
        if (!this.setting.formOperates || !this.setting.formOperates.length) return true
        let arr = this.setting.formOperates.filter(o => o.id === id) || []
        if (!arr.length) return true
        let item = arr[0]
        return item.read
      },
      judgeWrite(id) {
        if (!this.setting.formOperates || !this.setting.formOperates.length) return false
        let arr = this.setting.formOperates.filter(o => o.id === id) || []
        if (!arr.length) return true
        let item = arr[0]
        return !item.write
      },
      goBack() {
        this.$emit('refresh')
      },
      init(data) {
        this.dataForm.id = data.id || "";
        this.setting = data;
        this.visible = true;
        this.updateDataRule()
        this.$nextTick(() => {
          this.$refs['elForm'].resetFields();
          if (this.dataForm.id) {
            this.loading = true
            request({
              url: '/api/zgyf/AssoInfo/' + this.dataForm.id,
              method: 'get'
            }).then(res => {
              this.dataInfo(res.data)
              this.loading = false
            })
          }
          this.$emit('setPageLoad')
          this.getAssoInfoTypeListData()
        })
        this.$store.commit('generator/UPDATE_RELATION_DATA', {})
      },
      updateDataRule() {
        let newRules = {}
        for (let i = 0; i < this.setting.formOperates.length; i++) {
          const item = this.setting.formOperates[i]
          if (!item.id.includes('-')) {
            const newRulesItem = {
              required: item.required,
              message: item.name + '不能为空',
              trigger: item.trigger || 'blur'
            }
            if (!this.dataRule.hasOwnProperty(item.id)) {
              if (item.required) this.$set(newRules, item.id, [newRulesItem])
            } else {
              let withoutRequiredItem = true
              for (let i = 0; i < this.dataRule[item.id].length; i++) {
                if (this.dataRule[item.id][i].hasOwnProperty('required')) {
                  this.dataRule[item.id][i].required = item.required
                  withoutRequiredItem = false
                }
              }
              if (withoutRequiredItem && item.required) this.dataRule[item.id].push(newRulesItem)
            }
          } else {
            let key = item.id.split('-')[0]
            let newId = item.id.split('-')[1]
            let newItem = {
              ...item,
              id: newId
            }
            if (!this.tableRequiredData.hasOwnProperty(key)) {
              this.$set(this.tableRequiredData, key, [newItem])
            } else {
              this.tableRequiredData[key].push(newItem)
            }
          }
        }
        this.dataRule = {
          ...this.dataRule,
          ...newRules
        }
      },
      exist() {
        let isOk = true
        for (let key in this.tableRequiredData) {
          if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
            for (let i = 0; i < this.dataForm[key].length; i++) {
              let item = this.dataForm[key][i]
              inner: for (let id in item) {
                let arr = this.tableRequiredData[key].filter(o => o.id === id) || []
                if (!arr.length) continue inner
                if (arr[0].required) {
                  let msg = `${arr[0].name}不能为空`
                  let boo = true
                  if (arr[0].dataType === 'array') {
                    boo = !this.jnpf.isEmptyArray(item[id])
                  } else {
                    boo = !this.jnpf.isEmpty(item[id])
                  }
                  if (!boo) {
                    this.$message({
                      message: msg,
                      type: 'error',
                      duration: 1000
                    })
                    isOk = false
                    break
                  }
                }
              }
            }
          }
        }
        return isOk
      },
      judgeRequired(id) {
        if (!this.formOperates || !this.formOperates.length) return false
        let arr = this.formOperates.filter(o => o.id === id) || []
        if (!arr.length) return false
        let item = arr[0]
        return item.required
      },
      // 表单提交
      dataFormSubmit(eventType, flowUrgent) {
        this.$refs['elForm'].validate((valid) => {
          if (valid) {
            if (this.exist && !this.exist()) return
            if (eventType === 'audit' || eventType === 'reject') {
              this.$emit('eventReceiver', this.dataForm, eventType)
              return
            }
            this.dataForm.status = eventType === 'submit' ? 0 : 1
            this.dataForm.flowId = this.setting.flowId
            this.dataForm.flowUrgent = flowUrgent
            this.eventType = eventType
            if (this.eventType === 'submit') {
              this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
                type: 'warning'
              }).then(() => {
                this.request()
              }).catch(() => {});
            } else {
              this.request()
            }
          }
        })
      },
      request() {
        var _data = this.dataList()
        if (!this.dataForm.id) {
          request({
            url: '/api/zgyf/AssoInfo',
            method: 'post',
            data: _data
          }).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.visible = false
                this.$emit('close', true)
              }
            })
          })
        } else {
          request({
            url: '/api/zgyf/AssoInfo/' + this.dataForm.id,
            method: 'PUT',
            data: _data
          }).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.visible = false
                this.$emit('close', true)
              }
            })
          })
        }
      },
      openSelectDialog(key) {
        this.currTableConf = this.addTableConf[key]
        this.currVmodel = key
        this.selectDialogVisible = true
        this.$nextTick(() => {
          this.$refs.selectDialog.init()
        })
      },
      addForSelect(data) {
        for (let i = 0; i < data.length; i++) {
          let item = {
            ...this.tableRows[this.currVmodel],
            ...data[i]
          }
          this.dataForm[this.currVmodel].push(item)
        }
      },
      dataList() {
        var _data = JSON.parse(JSON.stringify(this.dataForm));
        _data.picture = JSON.stringify(_data.picture)
        _data.fileJson = JSON.stringify(_data.fileJson)
        return _data;
      },
      dataInfo(dataAll) {
        let _dataAll = dataAll
        _dataAll.picture = JSON.parse(_dataAll.picture)
        _dataAll.fileJson = JSON.parse(_dataAll.fileJson)
        this.dataForm = _dataAll
      },
      uploadImgChange(e){
        // 上传成功后，手动验证一次表单
        this.$refs['elForm'].validateField('picture')
      },
      uploadQuill(e){
        // 上传成功后，手动验证一次表单
        this.$refs['elForm'].validateField('detailedDescribe')
      }
    },
  }
</script>
